package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import io.netty.util.internal.StringUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        //解决缓存穿透
        // Shop shop = cacheClient.queryByIdPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //逻辑过期解决缓存击穿
        Shop shop = cacheClient.queryByIdLogicExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        if(shop == null){
            return Result.fail("店铺不存在");
        }

        return Result.ok(shop);
    }

    /**
     * 利用互斥锁解决缓存击穿
     * @param id
     * @return
     */
    public Shop queryByIdMutex(Long id) {
        //1,从redis中查询缓存
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2,判断是否存在
        if(StrUtil.isNotBlank(json)){
            //存在，返回
            Shop shop = JSONUtil.toBean(json, Shop.class);
            return shop;
        }
        if(json != null){
            //缓存穿透,当查出缓存为空时，返回错误，防止查询数据库
            return null;
        }
        //3,不存在则查询数据库
        //实现缓存重建
        Shop shop = null;
        try {
            Boolean isLock = lock(id);
            //获取锁
            //判断锁是否存在
            if (!isLock){
                Thread.sleep(50);
                return queryByIdMutex(id);
            }
            //存在则等待
            shop = getById(id);
            //4，不存在则报错
            if(shop == null){
                stringRedisTemplate.opsForValue().set( CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //5,写入缓存
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(id);
        }

        return shop;
    }




    /**对不存在的数据设置缓存空值
     * 逻辑：
     * 1,从redis中查询缓存
     * 2,判断是否存在
     * 3,不存在则查询数据库
     * 4,不存在则报错
     * 5,写入缓存
     * @param id
     * @return
     */

    public Shop queryByIdPassThrough(Long id) {
        //1,从redis中查询缓存
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2,判断是否存在
        if(StrUtil.isNotBlank(json)){
            //存在，返回
            Shop shop = JSONUtil.toBean(json, Shop.class);
            return shop;
        }
        if(json != null){
            //缓存穿透,当查出缓存为空时，返回错误，防止查询数据库
            return null;
        }
        //3,不存在则查询数据库
        Shop shop = getById(id);
        //4，不存在则报错
        if(shop == null){
            stringRedisTemplate.opsForValue().set( CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //5,写入缓存
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }
    private final static ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public Shop queryByIdLogicExpire(Long id) {
        //1,从redis中查询缓存
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2,判断是否存在
        if(StrUtil.isBlank(json)){

           return null;
        }
        //命中，反序列化json成对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        //判断是否逻辑过期
        LocalDateTime expireTime = redisData.getExpireTime();
        if(expireTime.isAfter(LocalDateTime.now())){
            //未过期，返回
            return shop;
        }
        //过期，进行缓存重建
        //获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = lock(id);
        //判断是否获取锁成功
        if(!isLock){
          //获取锁成功，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    this.SetLogicDataTimeout(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                finally {
                    unlock(id);
                }
            });
        }




        return shop;
    }


    @Override
    public Result updateShopById(Shop shop) {
        //1,判断店铺id
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }
        //2,更新数据库
        updateById(shop);

        //3,删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);

        return Result.ok();

    }

    private boolean lock(Long id) {
        Boolean setIfAbsent = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_SHOP_KEY + id, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(setIfAbsent);
    }
    private void unlock(Long id) {
        stringRedisTemplate.delete(LOCK_SHOP_KEY + id);
    }
/**
     * 逻辑过期解决缓存击穿
     * @param id
     * @return
     */
    public void SetLogicDataTimeout(Long id,Long expireTime) {
        Shop shop = getById( id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusMinutes(expireTime));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));

    }
}
